package io.chain.ko.security;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class JWTAuthProvider implements AuthenticationProvider {
	
	private UserDetailsService userDetailsService;
	
	public JWTAuthProvider(UserDetailsService userDetailsService) {
		this.userDetailsService = userDetailsService;
	}

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		String username=authentication.getName();
		String password=authentication.getCredentials().toString();
		Authentication auth=null;
		try {
			UserDetails userDetails=userDetailsService.loadUserByUsername(username);
			if(!password.equals(userDetails.getPassword())) {
				throw new BadCredentialsException("密码不正确");
			}
			auth = new UsernamePasswordAuthenticationToken(userDetails.getUsername(),userDetails.getPassword(),userDetails.getAuthorities());
		}catch (UsernameNotFoundException e) {
			throw new BadCredentialsException(e.getMessage());
		}
		
		return auth;
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return authentication.equals(UsernamePasswordAuthenticationToken.class);
	}

}
